package com.shop.service.impl;

import com.shop.common.Message;
import com.shop.common.OrderStatus;
import com.shop.common.ProductStatus;
import com.shop.dto.OrderDTO;
import com.shop.dto.OrderItemDTO;
import com.shop.entity.Member;
import com.shop.entity.Order;
import com.shop.entity.OrderItem;
import com.shop.entity.Product;
import com.shop.mapper.MemberMapper;
import com.shop.mapper.OrderItemMapper;
import com.shop.mapper.OrderMapper;
import com.shop.mapper.ProductMapper;
import com.shop.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单服务实现类
 * 
 * 提供订单相关的业务逻辑处理
 * 
 * @author Shop Management System
 * @version 1.0
 * @since 2024-01-01
 */
@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    
    private static final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);

    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private MemberMapper memberMapper;
    
    /**
     * 创建新订单
     * 1. 生成订单号、设置初始状态和时间
     * 2. 校验商品库存，扣减库存，组装订单项
     * 3. 计算总金额、折扣、实付金额
     * 4. 插入订单和订单项到数据库
     * 5. 返回完整订单对象
     */
    @Override
    public Order createOrder(OrderDTO orderDTO) {
        // 记录日志：开始创建订单
        log.info("Creating new order for memberId: {}", orderDTO.getMemberId());

        // 1. 构建订单对象，生成订单号、设置创建时间和初始状态
        Order order = new Order();
        order.setOrderNumber("ORD" + UUID.randomUUID().toString().substring(0, 8).toUpperCase()); // 订单号
        order.setCreatedAt(LocalDateTime.now()); // 创建时间
        order.setStatus(orderDTO.getStatus()); // 订单状态（可从DTO传入）
        order.setFinalAmount(orderDTO.getFinalAmount()); // 实付金额
        order.setRemark(orderDTO.getRemark()); // 备注
        order.setStatus(OrderStatus.STATUS_PENDING); // 默认待处理

            // 2. 处理订单项：校验库存、扣减库存、组装订单项对象（不插入数据库）
            List<OrderItem> orderItems = orderDTO.getOrderItems().stream().map(itemDTO -> {
                log.debug("Processing order item for productId: {}, quantity: {}", itemDTO.getProductId(), itemDTO.getQuantity());
                Product product = productMapper.findById(itemDTO.getProductId());
                // 校验商品是否存在且库存充足
                if (product == null || product.getStockQuantity() < itemDTO.getQuantity()) {
                    log.error("Product not found or stock insufficient for productId: {}", itemDTO.getProductId());
                    throw new RuntimeException(Message.NO_ENOUGH);
                }
                //判断商品销售状态
                if (product.getStatus().equals(ProductStatus.STATUS_DISABLE)){
                    throw new RuntimeException(Message.PRODUCT_STOP);
                }
                // 构建订单项对象
                OrderItem orderItem = new OrderItem();
                orderItem.setProductId(itemDTO.getProductId());
                orderItem.setQuantity(itemDTO.getQuantity());
                orderItem.setUnitPrice(itemDTO.getUnitPrice());
                orderItem.setTotalPrice(itemDTO.getQuantity() * itemDTO.getUnitPrice());
                
                // 扣减商品库存
                int newStock = product.getStockQuantity() - itemDTO.getQuantity();
                productMapper.updateStock(product.getId(), newStock);
                log.debug("Stock updated for productId: {}", product.getId());

                return orderItem;
            }).collect(Collectors.toList());

            // 3. 计算订单总金额
            double totalAmount = orderItems.stream().mapToDouble(OrderItem::getTotalPrice).sum();
            order.setTotalAmount(totalAmount);

            // 4. 如果有会员，设置会员ID并可扩展会员优惠逻辑
            if (orderDTO.getMemberId() != null) {
                Member member = memberMapper.findById(orderDTO.getMemberId());
                if (member != null) {
                    order.setMemberId(member.getId());
                    log.info("Applied discount for member: {}", member.getId());
                    // 可在此处扩展会员优惠逻辑
                }
            }
            
            // 5. 计算折扣金额（总金额-实付金额）
            order.setDiscountAmount(totalAmount - orderDTO.getFinalAmount());
            
            // 6. 插入订单，获取订单ID
            orderMapper.insert(order);
            log.info("Order {} created successfully.", order.getOrderNumber());

            // 7. 插入订单项，设置订单ID
            for (OrderItem item : orderItems) {
                item.setOrderId(order.getId());  // 绑定订单ID
                orderItemMapper.insert(item);
            }
            log.debug("{} order items saved for orderId: {}", orderItems.size(), order.getId());
            
            // 8. 设置订单项到订单对象，返回完整订单
            order.setOrderItems(orderItems);
            return order;
    }
    
    @Override
    public Order findOrderById(Long id) {
        return orderMapper.findById(id);
    }
    
    @Override
    public Order findOrderByNumber(String orderNumber) {
        return orderMapper.findByOrderNumber(orderNumber);
    }
    
    @Override
    public List<Order> findOrdersByMemberId(Long memberId) {
        return orderMapper.findByMemberId(memberId);
    }
    
    @Override
    public List<Order> findOrdersByStatus(String status) {
        return orderMapper.findByStatus(status);
    }
    
    @Override
    public List<Order> findOrdersByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return orderMapper.findByDateRange(startDate, endDate);
    }
    
    @Override
    public void updateOrderStatus(Long id, String status) {
        orderMapper.updateStatus(id, status);
    }
    
    @Override
    public Double getTotalSalesByDateRange(LocalDateTime startDate, LocalDateTime endDate) {
        return orderMapper.getTotalSalesByDateRange(startDate, endDate);
    }
    
    @Override
    public List<Order> findAllOrders() {
        return orderMapper.findAll();
    }

    @Override
    public void deleteOrderById(Long id) {
        Order order = orderMapper.findById(id);
        // 只允许删除已完成的订单
        if (OrderStatus.STATUS_COMPLETED.equals(order.getStatus())) {
            throw new RuntimeException(Message.ORDER_IS_OK);
        }
        // 先删除订单项
        orderItemMapper.deleteByOrderId(id);
        // 再删除订单
        orderMapper.deleteById(id);

        log.info("Order {} has been deleted", id);
    }
}